<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button v-if="isAuth('commodity:brand:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <el-button v-if="isAuth('commodity:brand:delete')" type="danger" @click="deleteHandle()"
                   :disabled="dataListSelections.length <= 0">批量删除
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="id"
        header-align="center"
        align="center"
        label="id">
      </el-table-column>
      <el-table-column
        prop="name"
        header-align="center"
        align="center"
        label="品牌名">
      </el-table-column>
      <el-table-column
        prop="logo"
        header-align="center"
        align="center"
        label="logo">
        <!--使用插槽机制，显示图片-->
        <template slot-scope="scope">
          <img :src="scope.row.logo" style="width: 90px">
        </template>
      </el-table-column>
      <el-table-column
        prop="description"
        header-align="center"
        align="center"
        label="说明">
      </el-table-column>
      <el-table-column
        prop="isshow"
        header-align="center"
        align="center"
        label="显示">
        <!--使用插槽机制-->
        <!--:active-value="1" integer需要加冒号-->
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isshow"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="switchIsShow(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="firstLetter"
        header-align="center"
        align="center"
        label="检索首字母">
      </el-table-column>
      <el-table-column
        prop="sort"
        header-align="center"
        align="center"
        label="排序">
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="170"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="relateCategoryHandle(scope.row.id)">关联分类</el-button>
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row.id,scope.row.name)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>

    <!-- 品牌和分类关联的对话框-->
    <el-dialog title="关联分类" :visible.sync="cateRelationDialogVisible" width="30%">
      <el-popover placement="right-end" v-model="popCatelogSelectVisible">
        <!--
        <category-cascader :catelogPath.sync="catelogPath"></category-cascader>-->
        <!-- 这里我们加入分类的Cascader 级联选择器, 前面我们使用过-->
        <el-cascader
          v-model="cascadedCategoryId"
          :options="categorys"
          :props="props">
        </el-cascader>
        <div style="text-align: right; margin: 0">
          <el-button size="mini" type="text" @click="popCatelogSelectVisible = false">取消</el-button>
          <el-button type="primary" size="mini" @click="addBrandCategoryRelation"> 确定</el-button>
        </div>
        <el-button slot="reference">新增关联</el-button>
      </el-popover>
      <el-table :data="cateRelationTableData" style="width: 100%">
        <el-table-column prop="id" label="id"></el-table-column>
        <el-table-column prop="brandName" label="品牌名"></el-table-column>
        <el-table-column prop="categoryName" label="分类名"></el-table-column>
        <el-table-column fixed="right" header-align="center" align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="deleteCateRelationHandle(scope.row.id,scope.row.brandId)"
            >移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cateRelationDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="cateRelationDialogVisible = false">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import AddOrUpdate from './brand-add-or-update'

export default {
  data () {
    return {
      dataForm: {
        key: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      //关联分类相关属性
      cateRelationDialogVisible: false,//显示对话框
      cateRelationTableData: [],//绑定品牌和分类品牌数据
      cascadedCategoryId: [],//级联选择器数据
      popCatelogSelectVisible: false,//el-popover 是否显示
      props: { //显示返回的家居分类的哪些字段/信息
        value: "id",
        label: "name",
        children: "childrenCategories"
      },
      categorys: [], //所有的家居分类-级联选择器
      brandId: 0,//记录选择的品牌id,
      relateCategoryForm:{}
    }
  },
  components: {
    AddOrUpdate
  },
  activated () {
    this.getDataList()
  },
  created () {
    this.getCategoryDataList()
  },
  methods: {
    deleteCateRelationHandle(id,brandId){//删除品牌id对应关联列表
      console.log("del-id",id)
      var ids = [id]
      this.$confirm(`确定对id=【${id}】进行删除操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/commodity/categorybrandrelation/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log('remove_res=', data)
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
            })
            //刷新列表
            this.getCategoryBrandRelation()
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(()=>{})//confirm取消报错
    },
    getCategoryBrandRelation() {//获取品牌id对应关联列表
      this.$http({
        //如果启动了网关服务, 则url 修改成走网关服务即可
        url: this.$http.adornUrl('/commodity/categorybrandrelation/brand/list'),
        method: "get",
        params: this.$http.adornParams({
          brandId: this.brandId
        })
      }).then(({ data }) => {
        console.log("data.data=", data)
        this.cateRelationTableData = data.data;
      });
    },
    addBrandCategoryRelation(){//新增品牌-分类关联表
      this.popCatelogSelectVisible = false;
      this.relateCategoryForm.brandId = this.brandId
      this.relateCategoryForm.categoryId = this.cascadedCategoryId[this.cascadedCategoryId.length - 1]
      this.$http({
        url: this.$http.adornUrl('/commodity/categorybrandrelation/save'),
        method: 'post',
        data: this.$http.adornData( this.relateCategoryForm,false)
      }).then(({data}) => {
        if (data && data.code === 0) {
          console.log('res=', data)
          this.$message({
            message: '添加成功',
            type: 'success',
            duration: 1500,
          })
          //刷新列表
          this.getCategoryBrandRelation()
        }
      })
    },
    // 获取分类列表-带有层级关系
    getCategoryDataList () {
      this.$http({
        url: this.$http.adornUrl('/commodity/category/list/tree'),
        method: 'get'
      }).then(({data}) => {
        if (data && data.code === 0) {
          console.log('res=', data)
          this.categorys = data.data
        }
      })
    },
    relateCategoryHandle (id) {//相应点击关联分类
      console.log('id', id)
      this.brandId = id
      this.cateRelationDialogVisible = true
      this.getCategoryBrandRelation()
    },
    switchIsShow (row) {// 切换是否显示
      console.log('点击切换row=', row)
      //对象解构
      let {id, isshow, name} = row
      this.$http({
        //url: 'http://localhost:9090/commodity/brand/update',
        url: this.$http.adornUrl('/commodity/brand/update'),
        method: 'post',
        data: this.$http.adornData({id, isshow, name}, false)
      }).then(({data}) => {
        if (data && data.code === 0) {
          console.log('res=', data)
          this.$message({
            message: '修改品牌显示状态成功',
            type: 'success',
            duration: 1500,
          })
        }
      })
    },
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      this.$http({
        //url: 'http://localhost:9090/commodity/brand/list',
        url: this.$http.adornUrl('/commodity/brand/list'),
        method: 'post',
        data: this.$http.adornParams({
          'pageNum': this.pageIndex,
          'pageSize': this.pageSize,
          'name': this.dataForm.key
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          console.log('data=', data)
          this.dataList = data.page.list
          //this.totalPage = data.page.totalCount
          this.totalPage = data.page.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 删除
    deleteHandle (id, name) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      // var names = []
      // //对选择的id进行操作
      // this.dataList.forEach(function (item){
      //   ids.forEach(function (id){
      //     if (item.id === id){
      //       names.push(item.name)
      //     }
      //   })
      // })
      var names = id ? [name] : this.dataListSelections.map(item => {
        return item.name
      })
      console.log('names=', names)
      this.$confirm(`确定对[name=${names.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          //url: 'http://localhost:9090/commodity/brand/delete',
          url: this.$http.adornUrl('/commodity/brand/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => {
      })//confirm取消报错
    }
  }
}
</script>
